using AutoMapper;
using BackData;
using Domain;
using Infratructure;
using MediatR;
using System.Transactions;
using Team.API.Applocation.Command.Quality;
using Yitter.IdGenerator;

namespace Team.API.Applocation.Hanldler.Quality
{
    /// <summary>
    /// 编辑质检工单处理器
    /// </summary>
    public class UpdateQualityHandler : IRequestHandler<UpdateQualityCommand, APIResult<int>>
    {
        private readonly IRepository<Qualitymodel> _qualiRep;
        private readonly IMapper _mapper;
        private readonly IRepository<Nlogmodel> _nlogRep;
        private readonly ILogger<UpdateQualityHandler> _logger;

        public UpdateQualityHandler(
            IRepository<Qualitymodel> qualiRep,
            IMapper mapper,
            IRepository<Nlogmodel> nlogRep,
            ILogger<UpdateQualityHandler> logger)
        {
            _qualiRep = qualiRep;
            _mapper = mapper;
            _nlogRep = nlogRep;
            _logger = logger;
        }

        public async Task<APIResult<int>> Handle(UpdateQualityCommand request, CancellationToken cancellationToken)
        {
            // 1. 查询质检工单是否存在
            var existingQuality = await _qualiRep.GetByIdAsync(request.Id);
            if (existingQuality == null || existingQuality.IsDel)
            {
                return new APIResult<int>
                {
                    Code = StateCode.Fail,
                    Message = "质检工单不存在",
                    Result = 0
                };
            }
            if(existingQuality.Status == 1)
            {
                return new APIResult<int>
                {
                    Code = StateCode.Fail,
                    Message = "质检工单已质检，请勿重复操作",
                    Result = 0
                };
            }
            // 2. 更新质检工单信息
            existingQuality.Quaworksubject = request.QualityDto.Quaworksubject;
            existingQuality.Quaworkcode = request.QualityDto.Quaworkcode;
            existingQuality.Quaworkname = request.QualityDto.Quaworkname;
            existingQuality.Orderid = request.QualityDto.Orderid;
            existingQuality.Completenum = request.QualityDto.Completenum;
            existingQuality.Qualifiednum = request.QualityDto.Qualifiednum;
            existingQuality.Defectivenum = request.QualityDto.Defectivenum;
            existingQuality.Itemid = request.QualityDto.Itemid;
            existingQuality.Status = 1;
            existingQuality.Processid = request.QualityDto.Processid;
            existingQuality.Processcount = request.QualityDto.Processcount;
            existingQuality.Reportingcount = request.QualityDto.Reportingcount;
            existingQuality.Inspectioncount = request.QualityDto.Inspectioncount;
            existingQuality.Reportingtime = request.QualityDto.Reportingtime;
            existingQuality.Accountid = request.QualityDto.Accountid;
            existingQuality.Meeage = request.QualityDto.Meeage;
            existingQuality.Updatetime = DateTime.Now;

            // 3. 创建操作日志
            var logModel = new Nlogmodel
            {
                Id = YitIdHelper.NextId(),
                Message = "编辑质检工单",
                Category = "Quality",
                Otherkey = request.Id,
                
            };

            var result = 0;
            var logResult = 0;

            // 4. 使用事务执行更新和日志记录
            using (TransactionScope tran = new TransactionScope(TransactionScopeAsyncFlowOption.Enabled))
            {
                try
                {
                    _logger.LogInformation($"{request.RealName}在{DateTime.Now}编辑了质检工单ID:{request.Id}");
                    result = await _qualiRep.UpdateAsync(existingQuality);
                    logResult = await _nlogRep.AddAsync(logModel);
                    tran.Complete();
                }
                catch (Exception ex)
                {
                    _logger.LogError($"编辑质检工单事务执行失败，发生回滚: {ex.Message}");
                    throw;
                }
            }

            if (logResult > 0)
            {
                return new APIResult<int>
                {
                    Code = StateCode.OK,
                    Message = "质检工单编辑成功",
                    Result = result
                };
            }
            else
            {
                return new APIResult<int>
                {
                    Code = StateCode.Fail,
                    Message = "质检工单编辑失败",
                    Result = result
                };
            }
        }
    }
}
